package com.tanhua.dubbo.api.mongo;

/**
 * @ClassName PeachblossomApiImpl
 * @Description TODO
 * @Author zxs
 * @Date 2021/4/20 11:09
 * Version 1.0
 */

import com.tanhua.domain.mongo.PeachBlossom;
import com.tanhua.domain.mongo.Voices;
import com.tanhua.domain.vo.PeachBlossomVo;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;


import java.util.List;

/**
 * 传音服务接口实现类
 */
@Service
public class PeachblossomApiImpl implements PeachblossomApi {


    @Autowired
    private MongoTemplate mongoTemplate;




    //桃花传音-发送语音
    @Override
    public Boolean save(PeachBlossom peachBlossom) {
        peachBlossom.setId(ObjectId.get());//主键id
        peachBlossom.setCreated(System.currentTimeMillis());//当前系统发布小视频时间
        PeachBlossom save = mongoTemplate.save(peachBlossom);
        if (save == null)
            return false;
        return true;
    }

    /**
     * @param userId
     * @return
     */
    @Override
    public PeachBlossom findVoice(Long userId,String gender) {
        //以下代码由莫虎提供
        Query query = new Query();
        //nin(userId)相当于not in 不在userId中的用户,同性 的不查询
        query.addCriteria(Criteria.where("userId").nin(userId).and("gender").nin(gender)).with(Sort.by(Sort.Order.desc("created"))).limit(50);
        List<PeachBlossom> peachBlossomList = mongoTemplate.find(query, PeachBlossom.class);
        //随机的index
        long total = mongoTemplate.count(query, PeachBlossom.class);
        int index = RandomUtils.nextInt(0,(int)total-1);
        PeachBlossom peachBlossom = peachBlossomList.get(index);
        return peachBlossom;
    }
}
